package com.open.center.common.model;

import java.util.UUID;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 通用结果对象
 *
 * @author Riche's
 * @since 2025/5/23
 */
@Schema(name = "CommonResult", description = "通用结果对象")
@Data
@NoArgsConstructor
public class CommonResult<T> {

    private String requestId;

    @Schema(name = "success", description = "请求是否成功")
    private boolean success = false;

    @Schema(name = "code", description = "响应码：200(成功)")
    private int code;

    @Schema(name = "message", description = "描述信息")
    private String message;

    @Schema(name = "data", description = "业务数据")
    private T data;


    public enum ResponseCode {

        SUCCESSFUL(200, "操作成功"),

        FAILED(500, "操作异常");

        private final int value;

        private final String reasonPhrase;

        ResponseCode(int value, String reasonPhrase) {
            this.value = value;
            this.reasonPhrase = reasonPhrase;
        }

        public int value() {
            return value;
        }

        public String reasonPhrase() {
            return reasonPhrase;
        }
    }

    public CommonResult(int code, String message) {
        this.code = code;
        this.message = message;
        this.requestId = UUID.randomUUID().toString();
        if (ResponseCode.SUCCESSFUL.value() == code) {
            this.success = true;
        }
    }

    public CommonResult(ResponseCode responseCode) {
        this(responseCode.value, responseCode.reasonPhrase);
    }


    public CommonResult<T> setCode(int code) {
        this.code = code;
        if (ResponseCode.SUCCESSFUL.value() == code) {
            this.success = true;
        }
        return this;
    }

    public CommonResult<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public CommonResult<T> setData(T data) {
        this.data = data;
        return this;
    }

    public static <T> CommonResult<T> success() {
        return new CommonResult<>(ResponseCode.SUCCESSFUL);
    }

    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(ResponseCode.SUCCESSFUL).setData(data);
    }

    public static <T> CommonResult<T> fail() {
        return new CommonResult<>(ResponseCode.FAILED);
    }

    public static <T> CommonResult<T> fail(int code) {
        return new CommonResult<T>(ResponseCode.FAILED).setCode(code);
    }

    public static <T> CommonResult<T> fail(String message) {
        return new CommonResult<T>(ResponseCode.FAILED).setMessage(message);
    }

    public static <T> CommonResult<T> fail(int code, String message) {
        return new CommonResult<T>(ResponseCode.FAILED).setCode(code).setMessage(message);
    }
}
